import React,{useEffect} from 'react'
import { useParams } from 'umi'
import { Form,Button,Input,Spin } from 'antd'
import ImageUpload from '@/components/ImageUpload'
import api from '@/network/api'
import { useRequest,history } from 'umi'

// 自定义
import { FiledType } from './type'

const BannerPub: React.FC = () => {
    const {objectId} = useParams<any>()
    const {data,error,loading } = useRequest(() => {// 重置表单数据
       return api.getBannerByObjectId(objectId)
    })
    useEffect(() => {
        if (data) {
            form.setFieldsValue(data)
        }
    },[data])
    const form = Form.useForm()[0]
    const handleReset = () => {
        form.resetFields()
    }
    const handleSubmit = async (values) => {
        let res = await form.validateFields()
        if (res.errorFields) return
        // 发送网络请求
        await api.updateBanner({objectId,...values})
        // 跳转到列表页
        history.push('/banner/list')
    }
    
    
    return (
        <Spin spinning={loading}>
            <Form 
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ 
                maxWidth: 600,
                marginTop: 20,
            }}
            onFinish={handleSubmit}
            form={form}>
                <Form.Item<FiledType>
                name="title"
                label="活动名称"
                rules={[
                    { required: true, message: '请输入活动名'},
                    { min: 2,max: 10, message: '活动名至少2个字符,至多10个字符' },
                ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item<FiledType>
                name="link"
                label="活动链接"
                rules={[
                    { required: true, message: '请输入活动链接'},
                    { pattern: /^https?:\/\//, message: '请输入正确的链接' },
                ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item<FiledType>
                name="imgurl"
                label="活动图片"
                initialValue={data?.imgurl}
                rules={[
                    { required: true, message: '请上传活动图片'},
                ]}
                >
                    <ImageUpload defaultUrl={data?.imgurl} />
                </Form.Item>
                <Form.Item
                style={{
                    textAlign: 'center'
                }}
                >
                    <Button 
                    style={{
                        marginRight: 20
                    }}
                    type="primary" 
                    htmlType="submit">提交</Button>
                    <Button 
                    onClick={handleReset}
                    htmlType="button">重置</Button>
                </Form.Item>
            </Form>
        </Spin>
    )
}
export default BannerPub